package com.easyattendance.servlets;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.easyattendance.model.EmailSettings;
import com.easyattendance.services.AddSectionService;
import com.easyattendance.services.EmailService;

@WebServlet(name = "EmailServlet", urlPatterns = "/EmailServlet")
public class EmailServlet extends HttpServlet{

	private static final long serialVersionUID = -6400342275448317253L;

	protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {  
    	 
		response.setContentType("text/html;charset=UTF-8");
		boolean dispatcherFlag = false;
		
		EmailService emailService=new EmailService();
		AddSectionService addSectionService=new AddSectionService();
		 
		boolean result=false;
		
		String email_msg = request.getParameter("email_template");
		String gmail_id = request.getParameter("gmail_id");
		String gmail_pwd=request.getParameter("gmail_password");
		String send_mode="Mail";
		if(email_msg.isEmpty() || gmail_id.isEmpty() || gmail_pwd.isEmpty()){
			request.setAttribute("email_null_values", "All * fields are required.");
			dispatcherFlag = true;
		}else{
			EmailSettings newMailSetting = new EmailSettings();
			boolean res = emailService.ifMailSettingAlreadyExists(gmail_id);		
			
			if(!res){
				newMailSetting=new EmailSettings(gmail_id,gmail_pwd,email_msg,send_mode);
				String currentUser = (String) request.getSession().getAttribute("currentUser");
				newMailSetting.setSection(addSectionService.getSectionBySectionEmail(currentUser));
				result = emailService.addEmailSetting(newMailSetting);
			} else {
				request.setAttribute("email_exists", "Email setting for this section already exists.");
				dispatcherFlag = true;
			}			
			
			if(result){
				request.setAttribute("email_added", "Email setting added successfully.");
				dispatcherFlag = true;
			} else {
				request.setAttribute("email_not_added", "Email setting could not not added.");
				dispatcherFlag = true;
			}
		}
		if(dispatcherFlag){
			RequestDispatcher rd = request.getRequestDispatcher("views/section/generalSettings.jsp");
			rd.forward(request, response);
		}
}

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	@Override
	public String getServletInfo() {
		return "Short description";
	}

}
